// femaZone.do
// Inputs: intermediate, `state'_coords_spjoin.dbf
// Outputs: `st'_coords.csv, prop_FEMA_zone
// Date last updated: 1/27/2025

// This do file creates CSVs of property coordinates that must then be input to FEMA's flood hazard layer in ArcGIS to get the flood zones. It then imports the data created in ArcGIS that has the FEMA zone of each property and appends them into one file that can be merged to the main processed data. It creates a dummy variable that identifies if a property is in a FEMA flood zone. 

********************************************************************************	
*  Step 1: Save CSVs of property coordinates
********************************************************************************

// Use intermediate data, renaming 6ft to be underwater
	use "$pathf\intermediate.dta", clear
	ren underwater_6ft under
	
// Create csvs of property coordinates by state for use in ArcGIS
	* Create id variable
	egen id=group(state lon lat)
	
	* Loop through each state to save 
	foreach state in fl ct de ga ma md me nc nh nj ny pa ri sc va {
		* Keep only that state and necessary vars, exporting CSV
		preserve
		keep if state==strupper("`state'")
		keep state lat lon id
		export delimited using "$pathi\`state'_coords.csv", replace
		restore
	}
	
********************************************************************************	
*  Step 2: Use ArcGIS to make FEMA flood hazard layer shape files
********************************************************************************	
// Use ArcGIS to upload CSVs
	* Use the following link to access the FEMA FLood Hazard Zone layer in their ArcGIS directory: https://hazards.fema.gov/arcgis/rest/services/public/NFHL/MapServer/28
	* Use spjoin to combine with CSVs of property coordinates, saving `st'_coords_spjoin shape files
	

********************************************************************************	
*  Step 3: Create dummy from database about flood hazard zone and save
********************************************************************************
// Loop through each state, creating dummy for whether property is in FEMA zone and saving
	foreach state in fl ct de ga ma md me nc nh nj ny pa ri sc va {
		* Import database from ArcGIS output
		import dbase using "$pathi\`state'_coords_spjoin.dbf", clear
		
		* Keep necessary vars, make dummy including diff types of zone
		keep lat lon FLD_ZONE id
		gen fema_zone=(FLD_ZONE=="AE" | FLD_ZONE=="A" | FLD_ZONE=="AH" | FLD_ZONE=="AO" | FLD_ZONE=="D" | FLD_ZONE=="VE" | FLD_ZONE=="A99")
		
		* Temp file and save
		tempfile `state'
		save ``state''
	}

// Append all states, renaming latitude and longitude, dropping duplicates, and saving
	u `va', clear
	append using `sc' `ri' `pa' `ny' `nj' `nh' `nc' `me' `md' `ma' `ga' `fl' `de' `ct'
	rename lat fema_lat 
	rename lon fema_lon 
	duplicates drop id, force
	save "$pathi\prop_FEMA_zone.dta", replace
